'''
自定义分页组件
def pretty_list(request):
    # 需要分页的数据
    queryset = models.PrettyNum.objects.all()
    # 实例化类，并传入数据
    page_object = Pagination(request, queryset=queryset)
    context = {
        'queryset': page_object.page_queryset,  # 分完页的数据
        'page_string': page_object.html()    #页码
    }

    return render(request, 'pretty_list.html', context)

前端：
    {% for obj in queryset %}
        {{obj.xx}}
    {% endfor %}

    <ul class="pagination" style="float: left">
        {{ page_string }}
    </ul>
'''
from django.utils.safestring import mark_safe
import copy


class Pagination(object):

    def __init__(self, request, queryset, page_param='page', page_size=10, plus=5):
        '''
        :param request:请求的对象
        :param queryset:符合条件的数据（根据这个数据进行分页处理）
        :param page_param:在URL中传递的获取分页的参数， 如/pretty/list/?page=22
        :param page_size:每页展示多少条数据
        :param plus: 显示当前页的前或者后几页(根据页码来的)
        '''
        # 因为request.GET是不可修改的，所以深拷贝一份request参数
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True

        self.query_dict = query_dict
        self.page_param = page_param

        page = request.GET.get(page_param, '1')
        print('page', page)
        print('page', type(page))
        # isdecimal()判断数是否为一个十进制数
        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        self.page = page
        self.page_size = page_size
        self.start = (page - 1) * page_size
        self.end = page * page_size
        self.page_queryset = queryset[self.start:self.end]

        # 数据总条数
        total_count = queryset.count()
        # 数据总页码
        total_page_count, div = divmod(total_count, page_size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        self.plus = plus

    def html(self):
        # 计算出当前页面的前五页和后五页
        # 数据较少不足11页时
        if self.total_page_count < self.plus * 2 + 1:
            start_page = 1
            end_page = self.total_page_count
        else:
            #     数据库中的数据比较多>11页时
            # 当前页<5时（小极值）
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus + 1
            else:
                # 当前页面>5
                # 当前页面+5 >总页面(大极值)
                if self.page + self.plus > self.total_page_count:
                    start_page = self.total_page_count - (2 * self.plus)
                    end_page = self.total_page_count
                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus

        # 页码
        page_str_list = []

        # 首页
        self.query_dict.setlist(self.page_param, [1])
        page_str_list.append('<li><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode()))

        # 上一页
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [1])
            prev = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
        page_str_list.append(prev)

        for i in range(start_page, end_page + 1):
            if i == self.page:
                self.query_dict.setlist(self.page_param, [i])
                ele = '<li class="active"><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            else:
                self.query_dict.setlist(self.page_param, [i])
                ele = '<li><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            page_str_list.append(ele)

        # 下一页，因为列表是有顺序的，所以要放在下面
        if self.page < self.total_page_count:
            self.query_dict.setlist(self.page_param, [self.page + 1])
            next_page = '<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [self.total_page_count])
            next_page = '<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode())
        page_str_list.append(next_page)

        # 尾页
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        page_str_list.append('<li><a href="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))

        # 搜索功能

        search_string = '''
        <li>
        <form method="get" style="float: left; margin-left: -1px">
            <div class="input-group" style="width: 200px">
                <input type="text" name="page" class="form-control" placeholder="页码">
                <span class="input-group-btn">
                    <button class="btn btn-default" type="submit">跳转</button>
                </span>
            </div>  
        </form>
        </li>
        '''
        page_str_list.append(search_string)

        # 把列表中的值拼为字符串，使用''分割（）, mark_safe()方法可以使字符串转换为html页面
        page_string = mark_safe(''.join(page_str_list))
        return page_string
